// https://pcapi-xiaotuxian-front-devtest.itheima.net
import { useTokenStore } from '@/stores/modules/token'
import Request, { type HttpMethod, type HttpRequestConfig } from 'luch-request'
// 创建请求实例配置基地址
const service = new Request({
  baseURL: 'https://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 15 * 1000,
  custom: {
    loading: true,
  },
})

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    // 添加请求头
    if (config) {
      const token = useTokenStore()
      if (token.token) {
        config.header!.Authorization = token.token
      } else {
        uni.navigateTo({
          url: '/pages/login/login',
        })
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 添加响应拦截器
service.interceptors.response.use(
  (res) => {
    return res.data
  },
  (error) => {
    return Promise.reject(error)
  },
)

export interface ServiceResponse<T> {
  code: string
  msg: string
  result: T
}
// 封装请求工具
const request = <T>(
  url: string,
  method: HttpMethod = 'GET',
  submitData?: object,
  config?: HttpRequestConfig,
) => {
  return service.request<T, ServiceResponse<T>>({
    url: url,
    method: method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
    ...config,
  })
}
export { service, request }
